/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NetworkSerialConfigView.java
 *
 * Created on 12.Şub.2010, 17:56:38
 */
package org.testis.gui.mvc.view.testbed;

import org.testis.gui.mvc.controller.TestBedControllerList;
import org.testis.gui.mvc.controller.testbed.DirectSerialConfigController;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.utilities.ValidationUtils;
import org.testis.gui.mvc.view.AbstractViewPanel;
import org.testis.gui.mvc.view.AtofBaseDialog;
import org.testis.orm.testbed.refined.SerialConnectionRefined;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.Locale;
import javax.swing.JOptionPane;

/**
 *
 * @author selcuk
 */
public class DirectSerialConfigView extends AtofBaseDialog implements
        AbstractViewPanel, Validatable {

    private DirectSerialConfigController m_controller;
    private boolean m_editMode;
    private int m_directserialconfigId;

    /** Creates new form NetworkSerialConfigView */
    public DirectSerialConfigView(Frame owner, boolean modal, boolean editMode) {
        super(owner, modal);
        m_controller = TestBedControllerList.newInstance().getDirectSerialConfigController();
        m_editMode = editMode;
        initComponents();
        setFrameIcon("images/testbed/" + SerialConnectionRefined.TYPE_NAME.toLowerCase(
                Locale.ENGLISH) + ".png");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        portComboBox = new javax.swing.JComboBox();
        boundaryComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        dataBitComboBox = new javax.swing.JComboBox();
        parityComboBox = new javax.swing.JComboBox();
        stopBitComboBox = new javax.swing.JComboBox();
        flowControlComboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(getWindowTitle());
        setMinimumSize(new java.awt.Dimension(200, 200));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setText("Name");

        jLabel2.setText("Boundary ");

        jLabel3.setText("Port");

        saveButton.setText("Save");
        setDefaultButton(saveButton);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        portComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10" }));

        boundaryComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "110", "300", "1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200", "230400", "460800", "921600" }));

        jLabel4.setText("DataBit");

        jLabel5.setText("Parity ");

        jLabel6.setText("StopBit");

        jLabel7.setText("FlowControl");

        dataBitComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "6", "7", "8" }));

        parityComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "None", "Odd", "Even", "Mark", "Space" }));

        stopBitComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "1.5", "2" }));

        flowControlComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NONE", "RTSCTS_IN", "RTSCTS_OUT", "XONXOFF_IN", "XONXOFF_OUT" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4)
                            .addComponent(jLabel7)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(flowControlComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(stopBitComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(parityComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(dataBitComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(boundaryComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(portComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 112, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(portComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boundaryComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel4)
                    .addComponent(dataBitComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(parityComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stopBitComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cancelButton)
                            .addComponent(saveButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(flowControlComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);

        String name = nameTextField.getText();
        String boundary = getSelectedBoundary();
        int dataBit = getSelectedDataBit();
        int flowControl = getSelectedFlowControl();
        int parity = getSelectedParity();
        int port = getSelectedPort();
        int stopBit = getSelectedStopBit();

        if (m_editMode) {
            m_controller.operationSaveConfig(m_directserialconfigId, name,
                    boundary, dataBit, flowControl, parity, port, stopBit);
        } else {
            m_controller.operationAddConfig(name, boundary, dataBit, flowControl,
                    parity, port, stopBit);
        }
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setVisible(false);
        this.setEnabled(false);
        m_controller.operationCloseWindow();
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                DirectSerialConfigController.VISIBLE_PROPERTY)) {
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            m_directserialconfigId = val;
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.NAME_PROPERTY)) {
            String val = (String) evt.getNewValue();
            nameTextField.setText(val);
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.BOUNDARY_PROPERTY)) {
            String val = (String) evt.getNewValue();
            selectBoundaryComboBox(val);
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.PORT_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectPortCombobox(val.intValue());
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.DATABIT_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectDataBitCombobox(val.intValue());
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.PARITY_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectParityComboBox(val.intValue());
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.STOPBIT_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectStopBitComboBox(val.intValue());
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.FLOWCONTROL_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectFlowControlComboBox(val.intValue());
        } else if (evt.getPropertyName().equals(
                DirectSerialConfigController.ERROR_PROPERTY)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();
        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");
            valid = false;
        }
        if (!valid) {
            JOptionPane.showMessageDialog(null,
                    builder.toString(),
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }

    private String getWindowTitle() {
        if (m_editMode) {
            return new String("Edit Direct Serial Config");
        } else {
            return new String("Add New Direct Serial Config");
        }
    }

    private int getSelectedPort() {
        return portComboBox.getSelectedIndex();
    }

    private void selectPortCombobox(int portValue) {
        portComboBox.setSelectedIndex(portValue);
    }

    private String getSelectedBoundary() {
        return (String) boundaryComboBox.getSelectedItem();
    }

    private void selectBoundaryComboBox(String boundary) {
        boundaryComboBox.setSelectedItem(boundary);
    }

    private int getSelectedDataBit() {
        String val = (String) dataBitComboBox.getSelectedItem();
        return Integer.parseInt(val);
    }

    private void selectDataBitCombobox(int dataBit) {
        String val = String.valueOf(dataBit);
        dataBitComboBox.setSelectedItem(val);
    }

    private int getSelectedParity() {
        return parityComboBox.getSelectedIndex();
    }

    private void selectParityComboBox(int parity) {
        parityComboBox.setSelectedIndex(parity);
    }

    private int getSelectedStopBit() {
        int index = stopBitComboBox.getSelectedIndex();
        int result;
        switch (index) {
            case 0:
                result = 1;
                break;
            case 1:
                result = 3;
                break;
            case 2:
                result = 2;
                break;
            default:
                result = 1;
                break;
        }
        return result;
    }

    private void selectStopBitComboBox(int stopBit) {
        int index;
        switch (stopBit) {
            case 1:
                index = 0;
                break;
            case 2:
                index = 2;
                break;
            case 3:
                index = 1;
                break;
            default:
                index = 0;
                break;
        }
        stopBitComboBox.setSelectedIndex(index);
    }

    private int getSelectedFlowControl() {
        String selected = (String) flowControlComboBox.getSelectedItem();
        int value = 0;
        if (selected.equals("NONE")) {
            value = 0;
        } else if (selected.equals("RTSCTS_IN")) {
            value = 1;
        } else if (selected.equals("RTSCTS_OUT")) {
            value = 2;
        } else if (selected.equals("XONXOFF_IN")) {
            value = 4;
        } else if (selected.equals("XONXOFF_OUT")) {
            value = 8;
        }
        return value;
    }

    private void selectFlowControlComboBox(int flowControl) {
        int index = 0;
        switch (flowControl) {
            case 0:
                index = 0;
                break;
            case 1:
                index = 1;
                break;
            case 2:
                index = 2;
                break;
            case 4:
                index = 3;
                break;
            case 8:
                index = 4;
                break;
            default:
                break;
        }
        stopBitComboBox.setSelectedIndex(index);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boundaryComboBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox dataBitComboBox;
    private javax.swing.JComboBox flowControlComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JComboBox parityComboBox;
    private javax.swing.JComboBox portComboBox;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox stopBitComboBox;
    // End of variables declaration//GEN-END:variables
}
